require.config({
	paths:{
		"cookie":"jquery.cookie",
		"jquery":"jquery-1.11.3",
		"fly":"jquery.fly"
	}
})
require(["cookie","jquery","fly"],function(cookie,jquery,fly){
	$(function(){
		var cartStr = $.cookie("cart") ? $.cookie("cart") : "";
		if(cartStr){
			var cartObj = convertCartStrToObj(cartStr);
			for(var id in cartObj){
				var good = cartObj[id];
				$(".cart-img img").attr("src",good.src);
				$(".jqgoodName").html(good.name);
				$(".jqgoodInfo").html(good.info);
				//alert(good.name);
				$(".jqgoodPrice").html(good.price);
				$(".jqCartNum").val(good.num);
				//alert(good.num);
				//alert(good.price);
				$(".jqgoodSum").html(good.num*good.price);				
			}
			$(".push").click(function(){
				var cartStr = $.cookie("cart") ? $.cookie("cart") : "";
				var cartObj = convertCartStrToObj(cartStr);
				cartObj[id].num ++;
				//将页面上显示的数量加1
				$(this).siblings("input").val(cartObj[id].num);
				//更新页面上的小计
				$(".jqgoodSum").html(good.num*good.price);
				//$(this).parent().parent().siblings('.jqgoodSum').html(cartObj[id].num * cartObj[id].price + "");
				//alert(cartObj[id].price);
				//将信息放回cookie
				$.cookie('cart', convertObjToCartStr(cartObj), {
					expires: 7,
					path: "/"
				});
			})
			$(".reduse").click(function(){
				var cartStr = $.cookie("cart") ? $.cookie("cart") : "";
				var cartObj = convertCartStrToObj(cartStr);
				if(cartObj[id].num > 1){ //商品数量减少不能少于1
					cartObj[id].num --;
					//将页面上显示的数量减1
					$(this).siblings("input").val("" + cartObj[id].num);
					//更新页面上的小计
					$(this).parent().parent().siblings('.jqgoodSum').html(1111);
					//将信息放回cookie
					$.cookie('cart', convertObjToCartStr(cartObj), {
						expires: 7,
						path: "/"
					});
				}
				
				
			});
					
		}
	})
	function convertCartStrToObj(cartStr){
		if(!cartStr){
			return{};
		}
		var goods = cartStr.split(":");
		var obj = {};
		for(var i = 0; i < goods.length; i ++){
			var data = goods[i].split(",");
			obj[data[0]] = {
				name : data[1],
				price : data[2],
				num : data[3],
				src : data[4]
			}
		}
		return obj;
	}
	function convertObjToCartStr(obj){
		var cartStr = "";
//		遍历对象
		for(var id in obj){
			if(cartStr){
				cartStr += ":";
			}
			cartStr += id + "," + obj[id].name + "," + obj[id].price + "," + obj[id].num + "," + obj[id].src;
 		}
		return cartStr;
	}
})
